<?php
class EnBacImage{
	const IMAGEINTERLACE = 1, IMAGEDEBUG = 1,TextFont = 1;/* constants */
	static $path,$font='core/arial.ttf';/* properties */
	public $ImageStream,$sFileLocation,$interlace,$type;/* properties */

	function __destruct(){unset($this->ImageStream);}
	
	private function printError($sMessage, $sMethod = __METHOD__, $sLine = __LINE__){
		if(EnBacImage::IMAGEDEBUG == 1){echo $sMethod . "(" . $sLine . ") " . $sMessage;}
	}

	private function loadImage(){/* load a image from file */
		if((int)ini_get("memory_limit")<64){@ini_set("memory_limit","64M");}
		switch($this->type){
			case 1:	$this->ImageStream = @imagecreatefromgif($this->sFileLocation);break;
			case 2:	$this->ImageStream = @imagecreatefromjpeg($this->sFileLocation);break;
			default:	$this->ImageStream = @imagecreatefrompng($this->sFileLocation);break;
		}
	}
	
	private function saveImage($quality = 100){
		if($quality<70 || $quality>100){
			$quality = 100;	
		}
		if (EnBacImage::IMAGEINTERLACE){
			imageinterlace($this->ImageStream, 1);
		}
		imagejpeg($this->ImageStream,$this->sFileLocation,$quality);
				
		/*switch($this->type){
			case 1:
				if (EnBacImage::IMAGEINTERLACE){imageinterlace($this->ImageStream, 1);}
				imagegif($this->ImageStream,$this->sFileLocation);break;
			case 2:
				if (EnBacImage::IMAGEINTERLACE){imageinterlace($this->ImageStream, 1);}
				imagejpeg($this->ImageStream,$this->sFileLocation,100);break;
			default:
				imagepng($this->ImageStream,$this->sFileLocation);break;
		}*/
	}
	
	private function showImage($quality = 100){
		if($quality<70 || $quality>100){
			$quality = 100;	
		}
		imagejpeg($this->ImageStream,null,$quality);
		/*switch($this->type){
			case 1:		imagegif($this->ImageStream);break;
			case 2:		imagejpeg($this->ImageStream,null,100);break;
			default:	imagepng($this->ImageStream);break;
		}*/
	}
	
	private function setLocations($sFileName,$get_direct=false){
		$this->sFileLocation = ($get_direct ? '':EnBacImage::$path) . $sFileName;
	}
	
	private function initializeImageProperties(){
		/* get imagesize from file and set imagesize array */
		list($this->width, $this->height, $iType, $this->htmlattributes) = @getimagesize($this->sFileLocation);

		if (($this->width < 1) || ($this->height < 1)) {$this->printError('invalid imagesize',__METHOD__,__LINE__);}
		
		/* set the imahe type and mimetype */
		$this->type 	= $iType;
		$this->mimetype = 'image/jpeg';
		
		/*switch($iType) {
			case 1:	$this->mimetype = 'image/gif';break;
			case 2:	$this->mimetype = 'image/jpeg';break;
			default:$this->mimetype = 'image/png';break;
		}*/
	}

	public function loadfile($sFileName,$get_direct=false){
		$this->setLocations($sFileName,$get_direct);/* load an image from file into memory */
		if (file_exists($this->sFileLocation)){$this->initializeImageProperties();$this->loadImage();}
		else$this->printError('Khong tim thay file',__METHOD__,__LINE__);
	}

	public function savefile($sFileName = NULL,$quality = 100){
		if ((isset($sFileName)) && ($sFileName != '')){$this->setLocations($sFileName);}
		$this->saveImage($quality);
	}
	
	public function resize($iNewWidth, $iNewHeight){
		/* resize the memoryimage do not keep ratio */
		if(function_exists("imagecopyresampled")){
			$ResizedImageStream = imagecreatetruecolor($iNewWidth, $iNewHeight);
			imagecopyresampled($ResizedImageStream, $this->ImageStream, 0, 0, 0, 0, $iNewWidth, $iNewHeight, $this->width, $this->height);
		}
		else{
			$ResizedImageStream = imagecreate($iNewWidth, $iNewHeight);
			imagecopyresized($ResizedImageStream, $this->ImageStream, 0, 0, 0, 0, $iNewWidth, $iNewHeight, $this->width, $this->height);
		}

		$this->ImageStream = $ResizedImageStream;
		$this->width = $iNewWidth;
		$this->height = $iNewHeight;
		//$this->setImageOrientation();
	}
	
	/* resize image to given width (keep ratio) */
	public function resizetowidth($iNewWidth){$iNewHeight = ($iNewWidth / $this->width) * $this->height;$this->resize($iNewWidth,$iNewHeight);}
	
	/* resize image to given height (keep ratio) */
	public function resizetoheight($iNewHeight){$iNewWidth = ($iNewHeight / $this->height) * $this->width;$this->resize($iNewWidth,$iNewHeight);}
	
	/* write text on image */
	static function subString($str,$start,$num,$ext=false){
		if($num>strlen($str)-$start)
		$num=strlen($str)-$start;
		
		if($num<=0)return '';
		
		$pos=strpos(substr($str,$start+$num+1,strlen($str)-$start-$num-1),' ');
		$st	=substr($str,$start,$num+$pos+1);
		
		if($ext&&strlen($str)-$start>$num)$st.='..';
		
		return $st;
	}
	
	public function writetext($sText, $iFontSize = 10, $sTextColor = '223,0,0', $sFont = '', $iXPos = 5, $iYPos = 15, $iTextAngle = 0,$blur=false,$pos=0,$width=0,$height=0){
		if($sFont=='') $sFont=EnBacImage::$font;
		
		if (!$this->ImageStream) 
		$this->printError('image not loaded',__METHOD__,__LINE__);

		$white	 		= imagecolorallocate($this->ImageStream,255,255,255);
		$sTextColor		= '0,0,0';
		$aTextColor 	= explode(',',$sTextColor,3);
		$TextImageColor = imagecolorallocate($this->ImageStream,$aTextColor[0],$aTextColor[1],$aTextColor[2]);
		$iLineWidth 	= imagettfbbox($iFontSize, $iTextAngle, EnBacImage::$font, $sText);
		
		if($iLineWidth[2]>$width-$iXPos){
			$numChar=(int) (($width-$iXPos)*strlen($sText)/$iLineWidth[2]);
			$sText=EnBacImage::subString($sText,0,$numChar,true);
			$iLineWidth = 	imagettfbbox($iFontSize, $iTextAngle, EnBacImage::$font, $sText);
		}
		/*Array(
		    [0] => -1 //lower left corner, X position 
		    [1] => -1 //lower left corner, Y position 
		    [2] => 79 //lower right corner, X position 
		    [3] => -1 //lower right corner, Y position 
		    [4] => 79 //upper right corner, X position 
		    [5] => -9 //upper right corner, Y position 
		    [6] => -1 //upper left corner, X position 
		    [7] => -9 //upper left corner, Y position 
		)*/
		
		switch ($pos){
			case 1:// Top Right Align
				$iXPos = $width-$iLineWidth[2]-$iXPos;
				break;
			case 2:// Bottom Right Align
				$iXPos = $width-$iLineWidth[2]-$iXPos;
				$iYPos = $height-$iLineWidth[5]-$iYPos;
				break;
			case 3:// Bottom Left Align
				$im_w = 3 + $iLineWidth[4];
				$im_h = 4-$iLineWidth[5];
				$im = imagecreatetruecolor($im_w, $im_h);
				imagefill ($im, 0,0,$white);
				$width_start	= 0;
				$height_start	= $height-$im_h;
				imagecopy($this->ImageStream,$im,$width_start,$height_start,0,0, $im_w, $im_h);
				imagedestroy($im);
				$blur=false;
				
				$iXPos=1;
				$iYPos = $height-3;
				break;
		}
		
		if($blur){
			imagettftext($this->ImageStream, $iFontSize, $iTextAngle, $iXPos+1, $iYPos+1, $white, $sFont, $sText);
		}
		
		imagettftext($this->ImageStream, $iFontSize, $iTextAngle, $iXPos, $iYPos, $TextImageColor, $sFont, $sText);
	}

	static function getExtension($file) {
		$pos = strrpos($file, '.');
		if(!$pos) {
			return false;
		}
		$str = substr($file, $pos, strlen($file));
		return $str;
	}	
	
	static function thumbImageWithBackground($imageSource,$width=0,$height=0,$limit_size = 0,$max=false, $itemTitle = '', $have_title=0){
		if($max){
			$w_max   = 960;
			//$h_max   = 777;
			$h_max   = 500;
			$quality = 80;
		}
		else{
			$quality = 100;
		}
		
		if($imageSource == '' || !file_exists(EnBacImage::$path . UP_FOLDER . "/" . $imageSource) || (!$max && !$height && !$width)){
			header("HTTP/1.0 404 Not Found"); 
			echo "<h1>404 - Not Found!!</h1>";
			exit;
		}
		
		$file_ext = self::getExtension($imageSource);
		
		if($max){
			$thumbDir = "thumb_max/";
			
			if($have_title){
				if($itemTitle!=''){
					function base64_url_encode($input) {
						return str_replace('=','',strtr(base64_encode($input), '+/', '-_'));
					}
					
					$have_title = ','.base64_url_encode($itemTitle);
				}
				else{
					$have_title = ',';
				}
				
				/*if(strlen(basename($imageSource,$file_ext).$have_title.$file_ext)>=255){
					$thumbDir='';
				}
				*/
			}
			else{
				$have_title = '';
			}
		}
		elseif($height && $width){
			$thumbDir="thumb/{$width}_{$height}/";
		}
		elseif($width){
			$thumbDir="thumb_w".($limit_size?"l":"")."/{$width}/";
		}
		
		$get_direct_img = false;	
		
		if(CACHE_ON){
			$tempCacheDir	='';
			$tempCacheFile	='';
			
			$cacheDir	=$thumbDir . dirname($imageSource).'/';
			$tempCacheDir	=IMG_TEMP_DIR . $cacheDir;
				
			if($max){
				$cache_file 	= $cacheDir .basename($imageSource,$file_ext).$have_title.$file_ext;
				$tempCacheFile  = $tempCacheDir . basename($imageSource,$file_ext).$have_title.$file_ext;				
			}
			else{
				$cache_file 	= $thumbDir .$imageSource;
				$tempCacheFile  = $tempCacheDir . basename($imageSource);				
			}
			
			$checkCacheFile = CHECK_PATH . $cache_file;
			
			//Lấy cache ra:
			if(@file_exists($checkCacheFile)){@header("Location: ".IMG_CACHE_URL.$cache_file);exit;}
		}
		
		$thumbImage	=  &new EnBacImage();
		$thumbImage->loadfile(UP_FOLDER . "/" . $imageSource,$get_direct_img);
		
		if(!$thumbImage || !$thumbImage->height || !$thumbImage->width){
			header("HTTP/1.0 404 Not Found"); 
			echo "<h1>404 - Not Found!!!</h1>";
			exit;
		}
		
		
		if($max){//Chế độ view full ảnh
			$width			 = $thumbImage->width;
			$height			 = $thumbImage->height;
			
			if($thumbImage->width > $w_max || $thumbImage->height > $h_max){
				if(($thumbImage->width/$thumbImage->height) <= ($w_max/$h_max)){//Ảnh gốc cao hơn $h_max px
					$height	= $h_max;
					$thumbImage->resizetoheight($height);
					$width	= $thumbImage->width;
				}
				else{
					$width	= $w_max;
					$thumbImage->resizetowidth($width);
					$height	= $thumbImage->height;
				}
			}
			
			if($thumbImage->width<300 || $thumbImage->height<250){
				if($thumbImage->width<300){
					$width=300;
				}
				if($thumbImage->height<250){
					$height=250;
				}
				
				self::create_thumb($thumbImage,$width,$height);
			}
			
			self::logo_paint($thumbImage,$width,$height,$itemTitle);
		}
		else{
			self::create_thumb($thumbImage,$width,$height,$limit_size);
			self::logo_paint($thumbImage,$width,$height);
		}
		
		if(CACHE_ON && $cache_file){
			if (FTP_CACHE && $tempCacheFile && ImageLib::CheckDir($tempCacheDir) && ImageLib::ftp_check_dir($cacheDir)){//Che do ghi cache qua ftp
				
				$thumbImage->savefile($tempCacheFile,$quality);
				
				if(@file_exists($tempCacheFile)){//upload file via ftp
					ImageLib::ftp_image_delete_file($cache_file);
					ImageLib::ftp_image_put_file($cache_file,$tempCacheFile);
					@unlink($tempCacheFile);
					ImageLib::ftp_image_close();
				}
			}
			elseif(ImageLib::CheckDir($cacheDir)){
				$thumbImage->savefile($cache_file,$quality);
			}
			
			if(!FIRST_SHOW_IMAGE && @file_exists($checkCacheFile)){
				@header("Location: ".IMG_CACHE_URL.$cache_file);
				imagedestroy($thumbImage->ImageStream);
				exit;
			}
		}
		
		//show img
		if(SET_HEADER){
			//standard method # 
			header('HTTP/1.0 200 OK'); //HTTP/1.1 200 OK
			//CGI method # 
			header('Status: 200 OK');
			
			header("Expires: ");
			header("Last-Modified: ");
			header('Cache-Control: public,max-age=2592000'); //Adjust maxage appropriately
			header('Pragma: public');//header("Cache-Control: public, must-revalidate");header("Pragma: hack");
		}

		//header("Cache-Control: no-cache");
 		//header("Pragma: no-cache");
 			 	
		if(stripos($_SERVER['HTTP_USER_AGENT'],"msie")===false){
			header('Content-type: '.$thumbImage->mimetype);
		}
		
		if(SET_HEADER){
			header('Content-Disposition: inline; filename='.basename($imageSource,$file_ext));
		}
		
		$thumbImage->showImage($quality);
		
		imagedestroy($thumbImage->ImageStream);
		exit;
	}
	
	static function thumbImageNoBG($imageSource,$width=0,$height=0){
		if($width<=0 && $height<=0) return '';
		
		if($imageSource!='')
		{
			if(!file_exists(EnBacImage::$path . UP_FOLDER . "/" . $imageSource))
			$imageSource=DEFAULT_IMAGE;
		}
		else 
			$imageSource=DEFAULT_IMAGE;
			
		$file_ext = self::getExtension($imageSource);
		
		if($height && $width){
			$thumbDir="thumb_in/{$width}_{$height}/";
		}
		else 
			$thumbDir = '';
		
		if($thumbDir && $imageSource == DEFAULT_IMAGE){//Nếu ở chế độ view ảnh thumb mà k thấy ảnh gốc!
			header("HTTP/1.0 404 Not Found"); 
			echo "<h1>404 - Not Found!</h1>";
			exit;
		}

		$get_direct_img = false;	
		
		if(CACHE_ON){
			$tempCacheDir	='';
			$tempCacheFile	='';
			
			if($thumbDir){
				$cacheDir		= $thumbDir . dirname($imageSource).'/';
				$tempCacheDir	= IMG_TEMP_DIR . $cacheDir;
					
				$tempCacheFile  = $tempCacheDir . basename($imageSource);
				$cache_file 	= $thumbDir .$imageSource;
				
				$checkCacheFile = CHECK_PATH . $cache_file;
			}
			else{
				if($imageSource != DEFAULT_IMAGE){
					$cacheDir		=dirname($imageSource);
					
					if(strpos($imageSource,'category/')===0)	
					$cacheDir='category';
		
					$tempCacheDir	=$cacheDir;
							
					if( $cacheDir!='' && (is_dir($cacheDir) || $cacheDir=='category') && $cacheDir!='.' ){
						$cacheDir		=IMG_CACHE_PATH . $cacheDir.'/';
						$tempCacheDir	=IMG_TEMP_DIR . $cacheDir.'/';
					}
					else{
						$cacheDir		=IMG_CACHE_PATH . 'enbac/';
						$tempCacheDir	=IMG_TEMP_DIR . 'enbac/';
					}
				}
				else{
					$get_direct_img = true;
					$cacheDir		= IMG_CACHE_PATH . 'blank/';
					$tempCacheDir	= IMG_TEMP_DIR . 'blank/';
				}
				
				$QUERY_STRING=$_SERVER['QUERY_STRING'];
				
				if(isset($_GET['delimg'])){
					$QUERY_STRING=str_replace(array('delimg='.$_GET['delimg'].'&','&delimg='.$_GET['delimg'],'delimg='.$_GET['delimg']),'',$QUERY_STRING);
				}
				
				$cache_file     = md5(str_replace("&amp;","&",$QUERY_STRING)).$file_ext;
				$tempCacheFile  = $tempCacheDir . $cache_file;
				$cache_file 	= $cacheDir .$cache_file;
				
				$checkCacheFile = CHECK_PATH . $cache_file;
			}
			
			$del_cache = (int)(isset($_GET['delimg']) && (int)$_GET['delimg']==1);
			
			//Lấy cache ra:
			if(@file_exists($checkCacheFile) && !$del_cache){@header("Location: ".IMG_CACHE_URL.$cache_file);exit;}
		}
		
		$thumbImage	= new EnBacImage();
		$thumbImage->loadfile(UP_FOLDER . "/" . $imageSource,$get_direct_img);
			
		if($thumbImage->width > $width || $thumbImage->height > $height){	
			if(($thumbImage->width/$thumbImage->height) <= ($width/$height)){
				$thumbImage->resizetoheight($height);
			}
			else{
				$thumbImage->resizetowidth($width);
			}
		}
		
		if(CACHE_ON && $cache_file){
			if (FTP_CACHE && $tempCacheFile && ImageLib::CheckDir($tempCacheDir) && ImageLib::ftp_check_dir($cacheDir)){//Che do ghi cache qua ftp
				
				$thumbImage->savefile($tempCacheFile);
				
				if(@file_exists($tempCacheFile)){//upload file via ftp
					ImageLib::ftp_image_delete_file($cache_file);
					ImageLib::ftp_image_put_file($cache_file,$tempCacheFile);
					@unlink($tempCacheFile);
					ImageLib::ftp_image_close();
				}
			}
			elseif(ImageLib::CheckDir($cacheDir)){
				$thumbImage->savefile($cache_file);
			}
			
			if(!FIRST_SHOW_IMAGE && @file_exists($checkCacheFile)){
				@header("Location: ".IMG_CACHE_URL.$cache_file);
				imagedestroy($thumbImage->ImageStream);
				exit;
			}
		}
		
		//show img
		if(SET_HEADER){
			//standard method # 
			header('HTTP/1.0 200 OK'); //HTTP/1.1 200 OK
			//CGI method # 
			header('Status: 200 OK');
			
			header("Expires: ");
			header("Last-Modified: ");
			header('Cache-Control: public,max-age=2592000'); //Adjust maxage appropriately
			header('Pragma: public');//header("Cache-Control: public, must-revalidate");header("Pragma: hack");
		}

		if(stripos($_SERVER['HTTP_USER_AGENT'],"msie")===false){
			header('Content-type: '.$thumbImage->mimetype);
		}
		
		if(SET_HEADER){
			header('Content-Disposition: inline; filename='.basename($imageSource,$file_ext));
		}
		
		$thumbImage->showImage($quality);
			
			
		imagedestroy($thumbImage->ImageStream);
		exit;
	}
	
	//$mode = 0:fit in, 1: fit top out, 2: fit out
	static function create_thumb(&$thumbImage,&$width,&$height,$limit_size = 0){
		if($width<=0 || $height<=0){
			/*if($width && $width!=$thumbImage->width)
			{
				$thumbImage->resizetowidth($width);
				$height = $thumbImage->height;
			}
			elseif($height && $height!=$thumbImage->height)
			{
				$thumbImage->resizetoheight($height);
				$width = $thumbImage->width;
			}*/
			
			if($width && $width!=$thumbImage->width)
			{
				if($width < $thumbImage->width)
				{
					$thumbImage->resizetowidth($width);
					$height = $thumbImage->height;
				}
				else
				{
					self::create_thumb($thumbImage,$width,$thumbImage->height);
				}
			}
			elseif($height && $height!=$thumbImage->height)
			{
				$thumbImage->resizetoheight($height);
				$width = $thumbImage->width;
			}
			
			/*if($limit_size && $height >= 2*$width){//Nếu đặt option giới hạn độ cao -> cắt bớt
				$height		= 2*$width;*/
			if($limit_size && $height >= 1.5 * $width){//Nếu đặt option giới hạn độ cao -> cắt bớt
				$height		= 1.5 * $width;
					
				$width_start	= ($width - $thumbImage->width)/2;
				$height_start	= 0;
				
				$image_bg	= &new EnBacImage();
				$image_bg->loadfile('core/bg.jpg',true);
				$image_bg->resize($width,$height);
				
				$image_bg	= $image_bg->ImageStream;
				
				imagecopy($image_bg,$thumbImage->ImageStream,$width_start,$height_start,0,0, $thumbImage->width, $thumbImage->height);
				imagedestroy($thumbImage->ImageStream);
				$thumbImage->ImageStream = $image_bg;
			}
		}
		elseif($thumbImage->width > $width || $thumbImage->height > $height){	
			if(($thumbImage->width/$thumbImage->height) <= ($width/$height)){
				$thumbImage->resizetoheight($height);
				$width_start=	($width - $thumbImage->width)/2;
				
				$image_bg= &new EnBacImage();
				$image_bg->loadfile('core/bg.jpg',true);
				$image_bg->resize($width,$height);
				
				$image_bg = $image_bg->ImageStream;
				imagecopy($image_bg,$thumbImage->ImageStream,$width_start,0,0,0, $thumbImage->width, $height);
				imagedestroy($thumbImage->ImageStream);
				$thumbImage->ImageStream = $image_bg;
			}
			else{
				$thumbImage->resizetowidth($width);
				$height_start =	($height-$thumbImage->height)/2;
				
				$image_bg= &new EnBacImage();
				$image_bg->loadfile('core/bg.jpg',true);
				$image_bg->resize($width,$height);
				$image_bg = $image_bg->ImageStream;
				
				imagecopy($image_bg,$thumbImage->ImageStream,0,$height_start,0,0, $width, $thumbImage->height);
				imagedestroy($thumbImage->ImageStream);
				$thumbImage->ImageStream = $image_bg;
			}
		}
		else{
			$width_start	=	($width - $thumbImage->width)/2;
			$height_start	=	($height-$thumbImage->height)/2;
			
			$image_bg= &new EnBacImage();
			$image_bg->loadfile('core/bg.jpg',true);
			$image_bg->resize($width,$height);
			
			$image_bg	=	$image_bg->ImageStream;
			imagecopy($image_bg,$thumbImage->ImageStream,$width_start,$height_start,0,0, $thumbImage->width, $thumbImage->height);
			imagedestroy($thumbImage->ImageStream);
			$thumbImage->ImageStream = $image_bg;
		}
	}
	
	static function logo_paint(&$thumbImage,&$width,&$height,$itemTitle = ''){
		//Bắn logo vào ảnh
		/*if($width > 120)
		{
			//Bắn logo vào ảnh
			$objLogo = &new EnBacImage();
			
			if($width >= 360)
			{
				$objLogo->loadfile('core/logo.png');
			}
			else
			{
				$objLogo->loadfile('core/logo_s.png');
			}
			
			$width_start	=	(int)(($width 	- $objLogo->width)/2);
			$height_start	=	$height 		- $objLogo->height;
			
			if($height_start <0)
			$height_start	=	$thumbImage->height - $objLogo->height;
			
			imagecopy($thumbImage->ImageStream,$objLogo->ImageStream,$width_start,$height_start,0,0, $objLogo->width, $objLogo->height);
			
			imagedestroy($objLogo->ImageStream);
		}*/
		//End bắn logo vào ảnh
		
		/*
		//Bắn logo vào ảnh (OLD)
		$objLogo = &new EnBacImage();
		$objLogo->loadfile('core/logo.png',true);
		
		if($width - $objLogo->width && $height - $objLogo->height){
			$width_start	=	$width - $objLogo->width-3;
			$height_start	=	3;
			imagecopy($thumbImage->ImageStream,$objLogo->ImageStream,$width_start,$height_start,0,0, $objLogo->width, $objLogo->height);
		}
		imagedestroy($objLogo->ImageStream);*/
		//End bắn logo vào ảnh
		
		//Bắn text vào ảnh:
		$sTextColor 	= '0,0,0';
		$angle 		= 0;
		if($itemTitle!=''){
			$fontSize 	= 12;
			$xPos 		= 5;
			$yPos 		= 22;
			$thumbImage->writetext($itemTitle,$fontSize,  $sTextColor, EnBacImage::$font, $xPos, $yPos, $angle,true,3,$width,$height);
		}
	}
}
?>